// 合并导入语句
import React, { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
// 添加 iconfont 资源引入
// import 'https://at.alicdn.com/t/font_3489760_8k3fzr5x7th.css'
import {
  NavBar,
  Image,
  Button,
  Checkbox,
  Modal
} from 'antd-mobile'
import '../App.css'
import '../css/common.css'

 export default function Jie() {
  const navigate = useNavigate()
  const [selectedProducts, setSelectedProducts] = useState([])
  const [totalAmount, setTotalAmount] = useState(0)
  const [shippingFee] = useState(8.00)
  const [couponDiscount] = useState(10.00)
  const [paymentMethod, setPaymentMethod] = useState('wechat')
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  // 添加地址信息状态
  const [address, setAddress] = useState({
    name: '李晓辉',
    phone: '15088888888',
    address: '上海市长宁区长宁路创意产业园3期12幢502'
  })
  // 移除forceUpdate状态

  useEffect(() => {
    // 从后端API获取选中的商品信息
    const fetchSelectedProducts = async () => {
      try {
        setLoading(true)
        setError('')
        console.log('开始获取商品信息...');
        
        // 先尝试从localStorage中读取选中的商品
        const selectedProducts = localStorage.getItem('selectedProducts');
        console.log('从localStorage获取的商品信息:', selectedProducts);
        
        if (selectedProducts) {
          try {
            const products = JSON.parse(selectedProducts);
            console.log('解析后的商品信息:', products);
            if (products.length > 0) {
              setSelectedProducts(products);
              
              // 优先从localStorage读取总金额
              const storedTotalAmount = localStorage.getItem('totalAmount');
              if (storedTotalAmount) {
                setTotalAmount(parseFloat(storedTotalAmount));
              } else {
                // 没有存储的总金额时重新计算
                const amount = products.reduce((sum, product) => {
                  return sum + (product.price || 0) * (product.quantity || 1)
                }, 0);
                setTotalAmount(amount);
              }
              
              setLoading(false);
              return;
            }
          } catch (error) {
            console.error('解析选中的商品信息失败:', error);
          }
        }
        
        // 如果localStorage中没有有效的商品信息，从API获取
        const response = await fetch('http://localhost:3000/list')
        if (!response.ok) {
          throw new Error('网络响应异常: ' + response.status)
        }
        const data = await response.json()
        console.log('获取商品信息成功:', data);
        if (data.code === 200 && data.list && data.list.length > 0) {
          // 假设我们从列表中选取第一个商品作为示例
          const selected = [data.list[0]]
          setSelectedProducts(selected)
          // 计算总金额
          const amount = selected.reduce((sum, product) => {
            return sum + (product.price || 0) * (product.quantity || 1)
          }, 0)
          setTotalAmount(amount)
        } else {
          // 如果没有数据，设置默认商品
          console.log('没有获取到有效的商品数据，使用默认商品');
          setSelectedProducts([{
            title: '布洛芬分散片 10mg*12片/盒',
            price: 36.50,
            quantity: 1
          }])
          setTotalAmount(36.50)
        }
      } catch (err) {
        setError('获取商品信息失败: ' + err.message)
        console.error('获取商品信息失败:', err);
        // 出错时也设置默认商品
        setSelectedProducts([{
          title: '布洛芬分散片 10mg*12片/盒',
          price: 36.50,
          quantity: 1
        }])
        setTotalAmount(36.50)
      } finally {
        setLoading(false)
      }
    }

    // 从后端API获取地址信息
    const fetchAddress = async () => {
      try {
        console.log('开始从API获取地址信息...');
        const response = await fetch('http://localhost:3000/list3')
        if (!response.ok) {
          throw new Error('获取地址信息失败: ' + response.status)
        }
        const data = await response.json()
        console.log('从API获取地址信息成功:', data);
        if (data.code === 200 && data.list2 && data.list2.length > 0) {
          // 假设我们从列表中选取第一个地址作为示例
          const addressInfo = data.list2[0]
          setAddress({
            name: addressInfo.name || '李晓辉',
            phone: addressInfo.phone || '15088888888',
            address: `${addressInfo.di || ''} ${addressInfo.xiang || ''}`
          })
        } else {
          console.log('没有从API获取到有效的地址数据');
        }
      } catch (err) {
        console.error('从API获取地址信息失败:', err);
        // 出错时保持默认地址
      }
    }

    // 从localStorage获取选中的地址信息
    const getSelectedAddress = () => {
      const selectedAddress = localStorage.getItem('selectedAddress');
      console.log('从localStorage获取的地址信息:', selectedAddress);
      if (selectedAddress) {
        try {
          const addressInfo = JSON.parse(selectedAddress);
          console.log('解析后的地址信息:', addressInfo);
          // 确保地址信息包含必要的字段
          if (addressInfo.name && addressInfo.phone && addressInfo.address) {
            // 直接更新状态
            setAddress({
              name: addressInfo.name,
              phone: addressInfo.phone,
              address: addressInfo.address
            });
            console.log('地址状态已更新为选中的地址');
          } else {
            console.warn('地址信息不完整，使用默认地址');
            fetchAddress();
          }
          // 清除localStorage中的选中地址
          localStorage.removeItem('selectedAddress');
        } catch (error) {
          console.error('解析选中的地址信息失败:', error);
          fetchAddress();
        }
      } else {
        // 如果没有选中的地址，从后端获取
        console.log('没有从localStorage获取到地址信息，使用API地址');
        fetchAddress();
      }
    }

    // 添加延迟执行，确保能读取到最新的localStorage数据
    const timer = setTimeout(() => {
      fetchSelectedProducts();
      getSelectedAddress();
    }, 100);
    // 清除定时器
    return () => clearTimeout(timer);
    }, [])  // 清空依赖项数组，只在组件挂载时执行一次

  const back = () => {
    navigate('/')
  }

  const handlePayment = () => {
    // 实现支付逻辑，向后端发送支付请求
    Modal.alert({
      content: '支付功能开发中...',
    })
  }

  const finalAmount = totalAmount + shippingFee - couponDiscount

  return (
    <div style={{
      backgroundColor: '#f5f5f5',
      minHeight: '100vh',
      paddingBottom: '100px'
    }}>
      {/* 顶部导航栏 */}
      <div style={{
        backgroundColor: '#fff',
        padding: '12px 16px',
        borderBottom: '1px solid #f0f0f0',
        display: 'flex',
        alignItems: 'center',
        boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
      }}>
        <NavBar onBack={back} style={{
          fontSize: '18px',
          fontWeight: 'bold',
          color: '#333',
          flex: 1,
          textAlign: 'center'
        }}>确认订单</NavBar>

      </div>

      {/* 显示错误信息 */}
      {error && (
        <div style={{
          backgroundColor: '#fff1f0',
          color: '#ff4d4f',
          padding: '12px',
          margin: '12px',
          borderRadius: '8px'
        }}>
          {error}
        </div>
      )}

      {/* 显示加载状态 */}
      {loading && (
        <div style={{
          backgroundColor: '#fff',
          padding: '24px',
          margin: '12px',
          borderRadius: '8px',
          textAlign: 'center'
        }}>
          加载中...
        </div>
      )}

      {/* 收货地址 */}
      <div style={{
        backgroundColor: '#fff',
        margin: '12px',
        padding: '16px',
        borderRadius: '8px'
      }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          {/* 红色框内的地图图标 */}
          <div style={{
            width: '40px',
            height: '40px',
            borderRadius: '4px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            marginRight: '12px'
          }}>
            <svg t="1753168089161" className="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" width="32" height="32"><path d="M512 896c-200.533333-145.066667-298.666667-285.866667-298.666667-426.666667 0-166.4 132.266667-298.666667 298.666667-298.666666s298.666667 132.266667 298.666667 298.666666c0 140.8-98.133333 281.6-298.666667 426.666667z m0-119.466667c140.8-106.666667 213.333333-209.066667 213.333333-307.2 0-119.466667-93.866667-213.333333-213.333333-213.333333s-213.333333 93.866667-213.333333 213.333333c0 98.133333 72.533333 200.533333 213.333333 307.2z m0-179.2c-72.533333 0-128-55.466667-128-128s55.466667-128 128-128 128 55.466667 128 128-55.466667 128-128 128 128z m0-85.333333c25.6 0 42.666667-17.066667 42.666667-42.666667s-17.066667-42.666667-42.666667-42.666666-42.666667 17.066667-42.666667 42.666666 17.066667 42.666667 42.666667 42.666667z" fill="#1fc29d"></path></svg>
          </div>
          
          <div style={{ flex: 1 }}>
            <div style={{
              fontSize: '16px',
              fontWeight: 'bold',
              color: '#333',
              display: 'inline-block',
              marginRight: '16px'
            }}>
              {address.name}
            </div>
            <div style={{
              fontSize: '14px',
              color: '#666',
              display: 'inline-block',
              marginBottom: '8px'
            }}>
              {address.phone}
            </div>
            <div style={{
              fontSize: '14px',
              color: '#666',
              lineHeight: '1.4',
              clear: 'both',
              whiteSpace: 'nowrap',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              maxWidth: 'calc(100% - 20px)'
            }}>
              {address.address}
            </div>
          </div>
          
          {/* 黄色框内的右侧箭头 */}
          <div style={{
            width: '40px',
            height: '40px',
            borderRadius: '4px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            cursor: 'pointer'
          }} onClick={() => navigate('/zhi')}>
            <svg t="1753168414682" className="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" width="20" height="20"><path d="M267.349333 97.450667a40.021333 40.021333 0 0 1 56.490667-2.986667L747.52 475.733333a39.936 39.936 0 0 1 21.333333 34.304l0.085334 2.133334a39.253333 39.253333 0 0 1-21.418667 36.352l-423.68 381.269333a40.021333 40.021333 0 1 1-53.589333-59.392L668.16 512.170667 270.250667 153.941333a40.021333 40.021333 0 0 1-2.901334-56.490666z" fill="#2c2c2c" p-id="20184"></path></svg>
          </div>
        </div>
      </div>

      {/* 处方信息 */}
      <div style={{
        backgroundColor: '#fff',
        margin: '12px',
        padding: '16px',
        borderRadius: '8px',
        textAlign: 'center'
      }}>
        <Button
          color='primary'
          size='small'
          style={{
            '--border-radius': '20px',
            '--background-color': '#fff',
            '--text-color': '#07c160',
            '--border-color': '#07c160',
            marginBottom: '8px',
            fontSize: '14px',
            border: '1px solid #07c160'
          }}
        >
          + 添加处方
        </Button>
        <div style={{
          fontSize: '12px',
          color: '#999'
        }}>
          药品中包含处方药，请凭处方购买
        </div>
      </div>

      {/* 商品列表 */}
      <div style={{
        backgroundColor: '#fff',
        margin: '12px',
        borderRadius: '8px',
        overflow: 'hidden'
      }}>
        {selectedProducts.map((product, index) => (
          <div key={index} style={{ padding: '16px', borderBottom: index < selectedProducts.length - 1 ? '1px solid #f0f0f0' : 'none', display: 'flex', alignItems: 'flex-start' }}>
            {/* 商品图片 */}
            <Image
              src={product.img || ''}
              fit='cover'
              width={80}
              height={80}
              style={{
                borderRadius: '8px',
                marginRight: '12px',
                position: 'relative',
                border: '2px solid #fff',
                boxShadow: '0 2px 8px rgba(255, 77, 79, 0.3)',
                flexShrink: 0
              }}
            />
            {/* 数量徽章 */}
            <div style={{
              position: 'absolute',
              bottom: 2,
              left: 2,
              width: 24,
              height: 24,
              backgroundColor: '#ff4d4f',
              borderRadius: '50%',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center',
              color: '#fff',
              fontSize: '12px',
              fontWeight: 'bold',
              border: '2px solid #fff',
              boxShadow: '0 1px 3px rgba(0,0,0,0.2)'
            }}>
              {product.quantity || 1}
            </div>
            {/* 商品信息 */}
            <div style={{ flex: 1 }}>
              <div style={{
                display: 'flex',
                alignItems: 'center',
                marginBottom: '6px'
              }}>
                <div style={{
                  backgroundColor: '#ff4d4f',
                  color: '#fff',
                  fontSize: '10px',
                  padding: '2px 4px',
                  borderRadius: '2px',
                  fontWeight: 'bold',
                  marginRight: '6px'
                }}>
                  Rx
                </div>
                <div style={{
                  fontSize: '14px',
                  fontWeight: '500',
                  lineHeight: '1.3',
                  color: '#333'
                }}>
                  {product.title}
                </div>
              </div>
              <div style={{
                fontSize: '12px',
                color: '#999',
                marginBottom: '8px',
                lineHeight: '1.4'
              }}>
                本品为处方药，请在医师指导下服用
              </div>
              <div style={{
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center'
              }}>
                <div style={{
                  fontSize: '16px',
                  color: '#ff4d4f',
                  fontWeight: 'bold'
                }}>
                  ¥ {product.price}
                </div>
                <div style={{
                  fontSize: '14px',
                  color: '#333',
                  marginLeft: '10px'
                }}>
                  x {product.quantity || 1}
                </div>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* 订单详情 */}
      <div style={{
        backgroundColor: '#fff',
        margin: '12px',
        borderRadius: '8px',
        overflow: 'hidden'
      }}>
        <div style={{
          padding: '12px 16px',
          borderBottom: '1px solid #f0f0f0',
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center'
        }}>
          <span style={{ fontSize: '14px', color: '#ff4d4f' }}>优惠券</span>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <span style={{ fontSize: '14px', color: '#ff4d4f', marginRight: '8px' }}>
              - ¥ {couponDiscount.toFixed(2)}
            </span>
            <i className="iconfont icon-arrow-right" style={{ fontSize: '14px', color: '#999' }}></i>
          </div>
        </div>
        <div style={{
          padding: '12px 16px',
          borderBottom: '1px solid #f0f0f0',
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center'
        }}>
          <span style={{ fontSize: '14px', color: '#333' }}>运费</span>
          <span style={{ fontSize: '14px', color: '#333' }}>¥ {shippingFee.toFixed(2)}</span>
        </div>
        <div style={{
          padding: '12px 16px',
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center'
        }}>
          <span style={{ fontSize: '14px', color: '#333' }}>合计</span>
          <span style={{ fontSize: '16px', color: '#333', fontWeight: 'bold' }}>
            ¥ {finalAmount.toFixed(2)}
          </span>
        </div>
      </div>

      {/* 支付方式 */}
      <div style={{
        backgroundColor: '#fff',
        margin: '12px',
        borderRadius: '8px',
        overflow: 'hidden'
      }}>
        <div style={{
          padding: '12px 16px',
          borderBottom: '1px solid #f0f0f0',
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center'
        }}>
          <div style={{ display: 'flex', alignItems: 'center' }}>
          <svg t="1753234624449" class="icon" viewBox="0 0 1144 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2620" width="16" height="16"><path d="M436.314353 632.771765c-68.517647 36.321882-78.667294-20.389647-78.667294-20.389647l-85.835294-190.524236c-33.039059-90.533647 28.581647-40.839529 28.581647-40.839529s52.856471 38.038588 93.003294 61.229176c40.086588 23.190588 85.835294 6.806588 85.835294 6.806589l561.212235-246.362353C936.899765 80.112941 765.891765 0 572.235294 0 256.180706 0 0 213.232941 0 476.310588c0 151.311059 84.811294 285.967059 216.937412 373.248l-23.792941 130.288941s-11.625412 38.038588 28.611764 20.389647c27.437176-12.047059 97.370353-55.115294 138.992941-81.347764 65.445647 21.684706 136.734118 33.731765 211.486118 33.731764 316.024471 0 572.235294-213.232941 572.235294-476.310588 0-76.197647-21.594353-148.178824-59.843764-212.028235-178.808471 102.309647-594.733176 340.118588-648.312471 368.489412z" fill="#43C93E" p-id="2621"></path></svg>
            <span style={{ fontSize: '14px', color: '#333' }}>微信支付</span>
          </div>
          <Checkbox
            checked={paymentMethod === 'wechat'}
            onChange={() => setPaymentMethod('wechat')}
            style={{
              '--icon-size': '18px',
              '--checked-color': '#07c160'
            }}
          />
        </div>
        <div style={{
          padding: '12px 16px',
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center'
        }}>
          <div style={{ display: 'flex', alignItems: 'center' }}>
          <svg t="1753234657152" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3964" width="16" height="16"><path d="M915.467633 814.19767 108.432083 814.19767c-23.060205 0-41.74373-18.696828-41.74373-41.74373L66.688353 452.42209l890.521986 0 0 320.03185C957.210339 795.499819 938.526815 814.19767 915.467633 814.19767M150.174789 730.71021 317.146639 730.71021l0-41.741683L150.174789 688.968527 150.174789 730.71021zM567.60697 605.481068 150.174789 605.481068l0 41.741683 417.432181 0L567.60697 605.481068zM66.688353 243.698325c0-23.059182 18.683525-41.74373 41.74373-41.74373l807.03555 0c23.059182 0 41.742706 18.684548 41.742706 41.74373l0 125.236306L66.688353 368.93463 66.688353 243.698325z" fill="#272636" p-id="3965"></path></svg>
            <span style={{ fontSize: '14px', color: '#333' }}>银行卡支付</span>
          </div>
          <Checkbox
            checked={paymentMethod === 'card'}
            onChange={() => setPaymentMethod('card')}
            style={{
              '--icon-size': '18px',
              '--checked-color': '#07c160'
            }}
          />
        </div>
      </div>

      {/* 底部支付栏 */}
      <div style={{
        position: 'fixed',
        bottom: 0,
        left: 0,
        right: 0,
        backgroundColor: '#fff',
        borderTop: '1px solid #e0e0e0',
        padding: '16px',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        zIndex: 999999,
        borderRadius: '12px 12px 0 0',
        boxShadow: '0 -2px 8px rgba(0,0,0,0.1)'
      }}>
        <div>
          <div style={{ fontSize: '12px', color: '#666' }}>实付金额</div>
          <div style={{
            fontSize: '18px',
            color: '#ff4d4f',
            fontWeight: 'bold'
          }}>
            ¥{finalAmount.toFixed(2)}
          </div>
        </div>
        <Button
          color='success'
          size='middle'
          onClick={handlePayment}
          style={{
            '--border-radius': '24px',
            '--background-color': '#07c160',
            '--text-color': '#fff',
            '--border-color': '#07c160',
            minWidth: '120px',
            height: '40px',
            fontSize: '16px',
            fontWeight: 'bold'
          }}
        >
          立即支付
        </Button>
      </div>
    </div>
  )
}

// export default Jie;
